#include <iostream>
#include <string>
#include <mysql/mysql.h>

using namespace std;

/**
 * C++ 代码连接数据库
 * 1. 使用时如下步骤
 * 2. 编译命令：g++ main.cpp -I/usr/include -L/usr/lib/x86_64-linux-gnu -lmysqlclient
 *      由于本系统存在环境变量，编译命令可简化为：g++ main.cpp -lmysqlclient
*/
int main(int argc, char* argv[])
{
    // 1. 初始化 MySQL 句柄
    MYSQL *con = mysql_init(NULL);

    // 2. 连接数据库时需要判断是否连接成功，
    auto ret = mysql_real_connect(con, "127.0.0.1", "li", "123456", "tallyBook", 0, NULL, CLIENT_MULTI_STATEMENTS);
    if(ret == nullptr) {
        cout << "connect database failed." << endl;
        return -1;
    }

    // 3. 查询数据库
    auto search_res = mysql_query(con, "select * from user;"); 

    // 4. 获取查询结果
    auto result = mysql_store_result(con);
    int col = mysql_num_fields(result);//获取列数
    int row = mysql_num_rows(result);//获取行数
    
    if(search_res == 0 && row != 0) {        
        for(int i = 0; i < result->row_count; i++) {
            auto info = mysql_fetch_row(result);//获取一行的信息
            cout<<"id: "<< info[0] << " name: "<< info[1] << " passwd: "<< info[2] << endl;
        }
    }

    return 0;
}
